package com.ycl.javacore.algorithm;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/25
 * Time: 10:35 AM
 * Desc: 二叉树前序遍历
 */
public class AlgoCast65Tree {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 递归方式
     *
     * @param root
     * @return
     */
    public List<Integer> preOrderTraversalRecursive(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preOrder(root, result);
        return result;
    }

    private void preOrder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        preOrder(root.left, result);
        preOrder(root.right, result);
    }

    public List<Integer> preOrderTraversalIterator(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                stack.add(node.left);
            }
        }
        return result;
    }

}
